﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace Zadanie2
{
    public delegate void ChangedEventHandler();

    class logika
    {
        public int n = 1;
        int delay;
        Semaphore sem;
        Thread[] thread;
        public bool[][] checks;
        int lWatkow;
        public event ChangedEventHandler Changed;

        public logika(int lWat, int del)
        {
            lWatkow = lWat;
            delay = del;
            checks = new bool[20][];
            sem = new Semaphore(1, 1);
            for (int i = 0; i < 20; i++)
            {
                checks[i] = new bool[20];
            }
            for (int i = 0; i < 20; i++)
            {
                for (int j = 0; j < 20; j++)
                {
                    checks[i][j] = true;
                }
            }
            checks[0][0] = false;
            stworzWatek();
        }

        private void stworzWatek()
        {
            thread = new Thread[lWatkow];
            for (int i = 0; i < lWatkow; i++)
            {
                thread[i] = new Thread(find);
                thread[i].Start();
            }
        }

        private int pobierzWartosc()
        {
            int licznik;
            sem.WaitOne();
            licznik = n;
            n += 1;
            sem.Release();
            return n;
        }

        public void killWatki()
        {
            foreach (Thread w in thread) w.Abort();
        }

        private void find()
        {
            while (true)
            {
                int licznik = pobierzWartosc();
                int i = licznik;
                i += licznik;
                while (i < 400)
                {
                    checks[(i - 1) % 20][(i - 1) / 20] = false;
                    i += licznik;
                }
                MessageBox.Show("Wiersz: " + ((i - 1) % 20).ToString() +
                    ", Kolumna: " + ((i - 1) / 20).ToString()+
                    ", i: "+ i.ToString());
                if (Changed != null)
                {
                    Changed();
                    System.Threading.Thread.Sleep(delay);
                }
            }
        }
    }
}
